Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java Method References

  • Java Method References provide a way to refer to a method as a function value instead of using a lambda expression.

  • There are four types of method references in Java:

  • 1.Reference to a static method
  • 2.Reference to an instance method of an object of a particular type
  • 3.Reference to an instance method of an existing object
  • 4.Reference to a constructor

Table Of Content

  • Java Method References
  • Reference to a static method
  • Reference to an instance method of an object of a particular type
  • Reference to an instance method of an existing object
  • Reference to a Constructor


Reference to a static method


ClassName::methodName

Here, ClassName is the name of the class that contains the static method and methodName is the name of the static method






import java.util.Arrays;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");

        // sort using lambda expression
        strings.sort((s1, s2) -> s1.compareTo(s2));

        // sort using static method reference
        strings.sort(String::compareTo);
    }
}

In this example, we have a list of strings and we want to sort it into ascending order. We can use the sort method of the List interface to sort the list.


A lambda expression (s1, s2) -> s1 is passed to sort in the first call. using the compareTo method, the function compareTo(s2) compares the two strings s1 and s2. We can use a string object to call the compareTo method, which is a String class instance method.






In the second call to sort, we use a static method reference String::compareTo. The compareTo method is a static method of the String class that takes two string arguments and returns an integer indicating their lexicographic order. Since compareTo is a static method, we can use the class name String to refer to it, followed by the method name compareTo, and use the double colon :: to indicate a method reference.


Both calls to sort will produce the same output, which is the list of strings sorted in ascending order. The second call using method reference is more concise and arguably easier to read


Reference to an instance method of an object of a particular type


object::methodName

Here,object refers to an object of a specific class and methodName is the name of a method used as an instance of that class.


import java.util.Arrays;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(new Person("Alice", 25), 
                                             new Person("Bob", 30),
                                             new Person("Charlie", 20));

        // sort using lambda expression
        people.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));

        // sort using instance method reference
        people.sort(Person::compareByName);

        // print sorted list
        for (Person p : people) {
            System.out.println(p.getName() + " " + p.getAge());
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static int compareByName(Person p1, Person p2) {
        return p1.getName().compareTo(p2.getName());
    }
}



Output:

Alice 25
Bob 30
Charlie 20 

Reference to an instance method of an existing object


In Java, you can use method references to refer to an instance method of an existing object. This is called an instance method reference with an object reference.


object::methodName

Here,object refers to an object of a specific class and methodName is the name of a method used as an instance of that class.


Java example of Reference to an instance method of an existing object
import java.util.ArrayList;
import java.util.List;

public class MethodReferenceExample {
    public static void main(String[] args) {
        // Create a list of integers
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        
        // Create an instance of the NumberPrinter class
        NumberPrinter numberPrinter = new NumberPrinter();
        
        // Use a method reference to call the print method on the numberPrinter object
        numbers.forEach(numberPrinter::print);
    }
}

class NumberPrinter {
    public void print(Integer number) {
        System.out.println("Number: " + number);
    }
}



Output:

Number: 1
Number: 2
Number: 3 

In this example, we create a list of integers and an instance of the NumberPrinter class. We then use a method reference to call the print method on the numberPrinter object for each element in the list using the forEach method.


The print method takes an Integer argument and simply prints the value to the console.


Note that the print method is an instance method, and we use the :: operator to reference it in the method reference. Also, since we are calling an instance method, we need to provide an instance of the NumberPrinter class to call the method on.




Reference to a Constructor


In Java, you can use method references to refer to a constructor of a class. This is called a constructor reference.


ClassName::new

It is used to create a new instance of the class





Java example of Reference to an instance method of an existing object
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, Person> personFactory1 = (name) -> new Person(name);
        Function<String, Person> personFactory2 = Person::new;

        Person p1 = personFactory1.apply("Alice");
        Person p2 = personFactory2.apply("Bob");

        System.out.println(p1.getName());
        System.out.println(p2.getName());
    }
}

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Output:

Alice
Bob
 

In this example, we have a Person class with a constructor that takes a String argument and initializes the name field. The Person class also has a getName method that returns the name field.


In the main method, we create two Function objects that take a String argument and return a Person object. The first Function object uses a lambda expression to create a new Person object with the given name. The second Function object uses a constructor reference to create a new Person object with the given name.





We then use the apply method of each Function object to create two Person objects p1 and p2. Finally, we print the names of the Person objects.



Functional Interfaces in Java Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.